package zj.com.fragments;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import zj.com.activities.CaptureActivity;
import zj.com.activities.DqrEditActivity;
import zj.com.activities.JcdRenSelectActivity;
import zj.com.activities.MipcaActivityCapture;
import zj.com.activities.SelectActivity;
import zj.com.activities.SelectJcdActivity;
import zj.com.activities.ZgCheckActivity;
import zj.com.app.ZjApplication;
import zj.com.model.Dic;
import zj.com.model.JcdInfoDB;
import zj.com.model.JcxDB;
import zj.com.model.PgScan;
import zj.com.model.User;
import zj.com.net.NetManager;
import zj.com.net.OnResponseListener;
import zj.com.util.Constants;
import zj.com.util.DateTimePickDialogUtil;
import zj.com.util.DateUtil;
import zj.com.util.DialogUtil;
import zj.com.util.LogUtils;
import zj.com.zj.R;

/**
 * Created by xi on 16/6/4.
 * 检查单信息
 */
public class JcdInfoFragment extends Fragment implements View.OnClickListener{

    public TextView jcd_tv;
    public TextView jc_type_tv;
    public TextView date_tv;
    public TextView gs_tv;
    public TextView prj_tv,jcr_tv,pt_tv;
    public EditText bz_et;

    public RelativeLayout gs_rl,prj_rl,jcd_rl,date_rl,pt_rl;
    public ImageView scan_iv,add_iv,jcr_scan_iv;
    public Intent intent;

    public RelativeLayout check_rl;
    public TextView check_value_tv;
    public View dqr_view;

    public static boolean isDqr = false;

    private String initStartDateTime = "2013年9月3日 14:44"; // 初始化开始时间
    public final int RQUEST_JCD = 0x2210;
    public final int RQUEST_SCAN = RQUEST_JCD+1;

    public final int JCR = RQUEST_JCD+2;
    public final int RQUEST_JCD_JCR = RQUEST_JCD+3;
    public final int RQUEST_SCAN_JCR = RQUEST_JCD+4;
    public JcdInfoDB jcdInfo ;



    public static String inspectItemId = "";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.fragment_jcd_info, container, false);
        initView(view);
        return view;
    }


    public void initView(View view){
        pt_tv = (TextView) view.findViewById(R.id.pt_tv);
        pt_rl = (RelativeLayout) view.findViewById(R.id.pt_rl);
        jcr_tv = (TextView) view.findViewById(R.id.jcr_tv);
        add_iv = (ImageView) view.findViewById(R.id.add_iv);
        add_iv.setOnClickListener(this);
        jcr_scan_iv = (ImageView) view.findViewById(R.id.jcr_scan_iv);
        jcr_scan_iv.setOnClickListener(this);
        dqr_view = view.findViewById(R.id.dqr_view);
        check_value_tv = (TextView) view.findViewById(R.id.check_value_tv);
        check_rl = (RelativeLayout) view.findViewById(R.id.check_rl);
        check_rl.setOnClickListener(this);
        gs_rl = (RelativeLayout) view.findViewById(R.id.gs_rl);
        gs_rl.setOnClickListener(this);
        prj_rl=  (RelativeLayout)view.findViewById(R.id.prj_rl);
        prj_rl.setOnClickListener(this);

        jcd_rl=  (RelativeLayout)view.findViewById(R.id.jcd_rl);
        jcd_rl.setOnClickListener(this);

        date_rl = (RelativeLayout) view.findViewById(R.id.date_rl);
        date_rl.setOnClickListener(this);

        jcd_tv = (TextView) view.findViewById(R.id.jcd_tv);
        jc_type_tv = (TextView) view.findViewById(R.id.jc_type_tv);
        //jc_type_tv.setOnClickListener(this);

        date_tv = (TextView) view.findViewById(R.id.date_tv);
        gs_tv = (TextView) view.findViewById(R.id.gs_tv);
        //gs_tv.setOnClickListener(this);


        prj_tv = (TextView) view.findViewById(R.id.prj_tv);
        //prj_tv.setOnClickListener(this);

        bz_et = (EditText) view.findViewById(R.id.bz_et);

        scan_iv = (ImageView) view.findViewById(R.id.scan_iv);
        scan_iv.setOnClickListener(this);

        if (isDqr) {
            scan_iv.setVisibility(View.GONE);
            bz_et.setEnabled(false);
            check_rl.setVisibility(View.VISIBLE);
            dqr_view.setVisibility(View.VISIBLE);
            add_iv.setVisibility(View.GONE);
            jcr_scan_iv.setVisibility(View.GONE);


            if(ZjApplication.isAcc == 0){
                check_rl.setVisibility(View.GONE);

            }

        }else{
            bz_et.setEnabled(true);
            check_rl.setVisibility(View.GONE);
            dqr_view.setVisibility(View.GONE);
            pt_rl.setVisibility(View.GONE);


        }
        if(!isDqr) {

            if (ZjApplication.isUpdateJcd) {

                jcd_tv.setText(ZjApplication.jcd.getInspectionNo());
                jc_type_tv.setText(ZjApplication.jcd.getInspectTypeName());
                initStartDateTime = ZjApplication.jcd.getInspectDate();
                gs_tv.setText(ZjApplication.jcd.getUnitName());
                prj_tv.setText(ZjApplication.jcd.getProjectName());
                bz_et.setText(ZjApplication.jcd.getInspectionRemark());
                jcr_tv.setText(ZjApplication.jcd.getJcr());



                if(ZjApplication.jcd.getJcr() != null){

                    userList = new ArrayList<>();
                    String jcr = ZjApplication.jcd.getJcr();
                    String[] jcrArray = jcr.split(",");
                    String[] idArray = ZjApplication.jcd.getJcr_id().split(",");
                    for(int i=0;i<jcrArray.length;i++){
                      String userName =   jcrArray[i];
                      String userId = idArray[i];
                       User user  = new User();
                        user.setUserID(userId);
                        user.setUserName(userName);
                        userList.add(user);
                    }

                }

                jcdInfo = ZjApplication.jcd;
                String date = ZjApplication.jcd.getInspectDate();
                initStartDateTime = date;
                date_tv.setText(DateUtil.formatStrimgDate3(ZjApplication.jcd.getInspectDate()));


            } else {
                Calendar calendar = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
                String dateTime = sdf.format(calendar.getTime());
                initStartDateTime = dateTime;
                date_tv.setText(DateUtil.formatStrimgDate3(initStartDateTime));

                String date = new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());

                jcd_tv.setText("JDC" + date);
                jcdInfo = new JcdInfoDB();
                ZjApplication.jcd = jcdInfo;
                jcdInfo.setInspectionNo("JDC" + date);
                jcdInfo.setInspectDate(dateTime);
            }


            bz_et.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {

                    if (s != null && jcdInfo != null) {
                        String result = s.toString();
                        jcdInfo.setInspectionRemark(result);
                    }
                }
            });
        }else{


            if(!TextUtils.isEmpty(inspectItemId)){
                obtainData(inspectItemId);

            }else{
                obtainData(ZjApplication.dqrJcdInfo.getServerInpsectId()+"");

            }
            //待确认



        }

    }

    public ProgressDialog dialog;
    public void obtainData(String id){

        dialog = DialogUtil.createProgressDialog(getActivity(), "提示", "数据获取中...");
        NetManager.getInstance(getActivity()).doGetInspectionDetail(id + "", new OnResponseListener<JcdInfoDB>() {
            @Override
            public void onComplete(boolean isOK, JcdInfoDB jcd, int errorCode, String errorMsg) {

                if(jcd == null && inspectItemId != ""){


                    Toast.makeText(getActivity(), "该任务已处理", Toast.LENGTH_SHORT).show();
                    getActivity().finish();
                    return;

                }

                if (isOK) {
                    ZjApplication.dqrJcdInfo = jcd;
                    initView(jcd);
                    dialog.dismiss();


                } else {
                    Toast.makeText(getActivity(), "获取失败", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                }

            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {

                Toast.makeText(getActivity(), "获取失败", Toast.LENGTH_SHORT).show();
                dialog.dismiss();

            }
        });
    }


    public void initView(JcdInfoDB jcd){
            jcd_tv.setText(jcd.getInspectionNo());
            jc_type_tv.setText(jcd.getInspectTypeName());
            String date = jcd.getInspectDate();
            date_tv.setText(DateUtil.formatStrimgDate2(date.replace("T", " ")));
            gs_tv.setText(jcd.getUnitName());
            prj_tv.setText(jcd.getProjectName());
            bz_et.setText(jcd.getInspectionRemark());

            String jcr = jcd.getInspector();
            LogUtils.getInstance().error("wxf=====jcr========="+jcr);
            if(jcr.equals("null")){
                jcr_tv.setText("");
            }else{
                jcr_tv.setText(jcd.getInspector());
            }
            if(ZjApplication.isAcc == 0){

                pt_tv.setText(jcd.getJcr());
                pt_rl.setVisibility(View.VISIBLE);
            }else{
                pt_rl.setVisibility(View.GONE);

            }
    }



    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();

        JcdInfoDB jcd =  ZjApplication.dqrJcdInfo;
        if(jcd == null){
            LogUtils.getInstance().error(" is nul.......");
//
//            String date = new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
//            jcd_tv.setText("JDC" + date);
//            jc_type_tv.setText("");
//            date_tv.setText("");
//            gs_tv.setText("");
//            prj_tv.setText("");
//            bz_et.setText("");
        }else{
            LogUtils.getInstance().error(" is not.......");

        }

    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onClick(View v) {

        if(isDqr){

            if(v.getId() == R.id.check_rl){

                intent = new Intent(getActivity(), ZgCheckActivity.class);
                startActivityForResult(intent, JCR);
            }
            return;
        }
        switch (v.getId()){
            case R.id.scan_iv:
                intent = new Intent(getActivity(), CaptureActivity.class);
                startActivityForResult(intent, RQUEST_SCAN);
                break;
            case R.id.jcd_rl:
                intent = new Intent(getActivity(),  SelectJcdActivity.class);
                intent.putExtra("dicType", Constants.InspectType);
                startActivityForResult(intent,RQUEST_JCD);
                break;
            case R.id.gs_rl:


                break;
            case R.id.prj_rl:

                break;
            case R.id.date_rl:
                DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
                        getActivity(), initStartDateTime,false);
                DateTimePickDialogUtil.isVisibleTime = false;
                dateTimePicKDialog.dateTimePicKDialog(date_tv);


                break;
            case R.id.add_iv:
                intent = new Intent(getActivity(), JcdRenSelectActivity.class);
                if(userList != null){
                    intent.putExtra("user",(Serializable)userList);
                }
                startActivityForResult(intent, RQUEST_JCD_JCR);
                break;
            case R.id.jcr_scan_iv:

                intent = new Intent(getActivity(), CaptureActivity.class);
                intent.putExtra("mode",1);
                if(userList != null && userList.size() > 0){
                    intent.putExtra("user",(Serializable)userList);

                }
                startActivityForResult(intent, RQUEST_SCAN_JCR);
                break;
        }
    }

    public User user;
    List<User> userList;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(resultCode == Activity.RESULT_OK){

            switch(requestCode){

                case JCR:
                    user = (User) data.getSerializableExtra("user");
                    if(user != null){
                        check_value_tv.setText(user.getUserName());
                        ZjApplication.checkUser = user;
                    }
                    break;
                case RQUEST_JCD_JCR:

                    StringBuffer sb = new StringBuffer();
                    StringBuffer userSb = new StringBuffer();
                    userList = (List<User>) data.getSerializableExtra("user");
                    if(userList != null){

                        for(User u:userList){
                            sb.append(u.getUserName());
                            sb.append(",");
                            userSb.append(u.getUserID());
                            userSb.append(",");
                        }
                        jcdInfo.setJcr(sb.toString());
                        jcdInfo.setJcr_id(userSb.toString());
                        jcr_tv.setText(sb.toString());
                    }
                    break;
                case RQUEST_SCAN_JCR:

                    userList = (List<User>) data.getSerializableExtra("user");
                    if(userList != null) {
                        StringBuffer sb2 = new StringBuffer();
                        StringBuffer userSb2 = new StringBuffer();


                        for (User u : userList) {
                            sb2.append(u.getUserName());
                            sb2.append(",");
                            userSb2.append(u.getUserID());
                            userSb2.append(",");
                        }
                        jcdInfo.setJcr(sb2.toString());
                        jcdInfo.setJcr_id(userSb2.toString());
                        jcr_tv.setText(sb2.toString());

                    }
                    break;

                case RQUEST_JCD:
                    Dic dic = (Dic) data.getSerializableExtra("dic");
                    jcdInfo.setInspectType(Integer.parseInt(dic.getValue()));
                    jcdInfo.setInspectTypeName(dic.getName());
                    jc_type_tv.setText(dic.getName());
                    break;
                case RQUEST_SCAN:


                    String result = data.getStringExtra("result");
                    LogUtils.getInstance().error(result);
                    if(result != null){

                      String[] s =   result.split("//");

                        LogUtils.getInstance().error("llllenght="+s.length);
                      if(s.length >=2){
                          result = s[1];
                      }
                    }
                    try{
                        JSONObject obj = new JSONObject(result);
                        String projectCode = obj.getString("projectCode");
                        String orgCode = obj.getString("orgCode");
                        String orgName = obj.getString("orgName");
                        String unitName = obj.getString("unitName");
                        String unitCode = obj.getString("unitCode");
                        String projectName = obj.getString("projectName");

                        PgScan pg = new PgScan();
                        pg.setOrgCode(orgCode);
                        pg.setOrgName(orgName);
                        pg.setProjectCode(projectCode);
                        pg.setUnitName(unitName);
                        pg.setUnitCode(unitCode);
                        pg.setProjectName(projectName);
                        ZjApplication.pgScan = pg;
                        gs_tv.setText(unitName);
                        prj_tv.setText(projectName);
                        jcdInfo.setInspectOrgCode(unitCode);
                        jcdInfo.setProjectName(projectName);
                        jcdInfo.setUnitName(unitName);
                        jcdInfo.setInspectProjectCode(projectCode);

                    }catch(Exception e){

                    }
                    LogUtils.getInstance().error(result);
                    break;

            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


}
